package cn.wuxing.mediation.common.core.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class OssComponent {
    @Value("${oss.KEY_ID}")
    private String KEY_ID;

    @Value("${oss.KEY_SECRET}")
    private String KEY_SECRET;

    @Value("${oss.ENDPOINT}")
    private String ENDPOINT;

    @Value("${oss.BUCKET_NAME}")
    private String BUCKET_NAME;

    @Value("${oss.DIR}")
    private String DIR;

    private OSS ossClient;

    public OSS getOssClient() {
        ossClient = new OSSClientBuilder().build(ENDPOINT, KEY_ID, KEY_SECRET);
        return ossClient;
    }

    public void ossClientShutDown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 文件上传 返回url
     *
     * @return
     */
    private FileVo uploadFile(MultipartFile file) {
        FileVo fileVo = new FileVo();
        OSS ossClient = getOssClient();

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装OSS上存储的路径
        String folder = dft.format(time);
        String fileName = generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = DIR + "/" + folder + "/" + fileName + extension;

        try {
            PutObjectResult result = ossClient.putObject(BUCKET_NAME, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                String url = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + uploadFileName;
                fileVo.setFileName(fileName + extension);
                fileVo.setUrl(url);
                fileVo.setNewFileName(url);
                fileVo.setOriginalFilename(file.getOriginalFilename());
                return fileVo;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}", e.getMessage());
        }
        return null;
    }

    /**
     * 单个文件 返回url
     *
     * @return
     */
    public FileVo upload(MultipartFile file) {
        FileVo fileVo = uploadFile(file);
        ossClientShutDown();
        return fileVo;
    }

    /**
     * 多个文件 返回urls
     *
     * @return
     */
    public List<FileVo> uploads(List<MultipartFile> multipartFiles) {
        List<FileVo> fileVos = new ArrayList<>();
        for (MultipartFile file : multipartFiles) {
            FileVo fileVo = uploadFile(file);
            fileVos.add(fileVo);
        }
        ossClientShutDown();
        return fileVos;
    }


    /**
     * 获取随机字符串
     *
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
    }
}
